/**
 * 
 */
package net.danielpaz.puc.poo.frigorifico.model;

/**
 * @author Junior
 *
 */
import java.sql.*;

public class FornecedorDAO {
	public BD bd;
	public Fornecedor fornecedor;
	private PreparedStatement statement;
	private ResultSet resultSet;
	private String men, sql;
	public static final byte INCLUSAO = 1;
	public static final byte ALTERACAO = 2;
	public static final byte EXCLUSAO = 3;

	public FornecedorDAO() {
		bd = new BD();
		fornecedor = new Fornecedor();
	}

	public boolean localizar() {
		sql = "select * from fornecedor where id = ?";
		try {
			statement = bd.connection.prepareStatement(sql);
			statement.setInt(1, fornecedor.getId());
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				fornecedor.setNome(resultSet.getString(1));
				fornecedor.setCnpj(resultSet.getString(2));

			}
			return true;
		} catch (SQLException erro) {
			erro.printStackTrace();
			return false;
		}
	}

	public String atualizar(int operacao) {
		men = "Operacao realizada com sucesso!";
		try {
			if (operacao == INCLUSAO) {
				sql = "insert into fornecedor (nome, cnpj) values (?,?)";
				statement = bd.connection.prepareStatement(sql);
				statement.setString(1, fornecedor.getNome());
				statement.setString(2, fornecedor.getCnpj());

			} else if (operacao == ALTERACAO) {
				sql = "update fornecedor set nome = ?, cnpj = ? "
						+ " where id = ?";
				statement = bd.connection.prepareStatement(sql);
				statement.setInt(3, fornecedor.getId());
				statement.setString(1, fornecedor.getNome());
				statement.setString(2, fornecedor.getCnpj());
			} else if (operacao == EXCLUSAO) {
				sql = "delete from fornecedor where id = ?";
				statement = bd.connection.prepareStatement(sql);
				statement.setInt(1, fornecedor.getId());
			}
			if (statement.executeUpdate() == 0)
				men = "Falha na operacao!";
		} catch (SQLException erro) {
			men = "Falha na operacao " + erro.toString();
		}
		return men;
	}
}